package com.finance.system.controller;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.finance.base.enums.OpearteEnum;
import com.finance.base.enums.StateEnum;
import com.finance.base.constant.BaseConstants;
import com.finance.base.enums.TargetEnum;
import com.finance.framework.controller.BaseController;
import com.finance.base.exception.BaseException;
import com.finance.framework.controller.Result;
import com.finance.framework.file.FileUtils;
import com.finance.framework.lang.BeanUtils;
import com.finance.rule.service.ISettingLogService;
import com.finance.system.bean.pojo.Organization;
import com.finance.system.export.OrganizationParse;
import com.finance.system.export.OrganizationImportTemplateBean;
import com.finance.system.request.OrganizationReq;
import com.finance.system.service.IOrganizationService;
import com.finance.system.bean.pojo.User;
import com.finance.util.export.ExportBuilder;
import com.finance.util.export.ExportFactory;
import com.finance.util.export.ImportUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by ljg on 2017/3/24.
 */
@Controller
@RequestMapping("/system/organization")
public class OrganizationController extends BaseController{

    @Resource
    private IOrganizationService organizationService;
    @Resource
    private ISettingLogService settingLogService;
    private ObjectMapper objectMapper=  new ObjectMapper();

    @RequestMapping("/index")
    public String index(){
        return "system/organization/index";
    }

    @RequestMapping("/list")
    public Result list(){
        List<Organization> organizations = organizationService.listAll();
        return getSuccessResult(organizations);
    }

    /**
     * 根据名字或者code 模糊查询组织机构
     * */
    @RequestMapping("/listbyname")
    public Result listByName(String key){
        List<Organization> organizations = organizationService.listByNameOrCode(key);
        return getSuccessResult(organizations);
    }



    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Result add(@Valid OrganizationReq form) throws BaseException {
        User user = getAuthUser();
        if(user == null){
            throw new BaseException(BaseConstants.ERR_UNKONW_USER);
        }
        Organization organization = convertBeanFromForm(form);

        organization.setCreateUid(user.getId());
        organization.setState(StateEnum.Valid.getState());
        organizationService.add(organization);
        return getSuccessResult("添加机构管理成功");
    }

    private Organization convertBeanFromForm(OrganizationReq orgin) {
        Organization organization = new Organization();
        try {
            BeanUtils.copyProperties(organization,orgin);
        } catch (Exception e) {
            throw new BaseException(BaseConstants.ERR_COPYBEAN);
        }
        return organization;
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Result update(String id,@Valid OrganizationReq form){
        if(StringUtils.isBlank(id)){
            throw new BaseException(BaseConstants.ERR_INVALID_PARAMETER);
        }
        Organization oldOrganization = organizationService.getById(Long.parseLong(id));
        if(oldOrganization == null){
            throw new BaseException(BaseConstants.ERR_NON_EXISTENT);
        }
        User user = getAuthUser();
        if(user == null){
            throw new BaseException(BaseConstants.ERR_UNKONW_USER);
        }
        Organization organization = convertBeanFromForm(form);
        organization.setUpdateUid(user.getId());
        organization.setId(Long.parseLong(id));
        organizationService.update(organization);

        String oldValue = null;
        try {
            oldValue = objectMapper.writeValueAsString(oldOrganization);
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(),e);
        }
        settingLogService.addLog(user, OpearteEnum.UPDATE,TargetEnum.ORGANIZATION_INFO,oldValue);

        return getSuccessResult(true);
    }

    @RequestMapping("/del")
    public Result del(String id){
        if (StringUtils.isBlank(id)){
            return getFailResult(BaseConstants.ERR_INVALID_PARAMETER,"参数缺失");
        }
        User user = getAuthUser();
        if(user == null){
            throw new BaseException(BaseConstants.ERR_UNKONW_USER);
        }
        boolean ret = organizationService.del(user.getId().toString(),Long.parseLong(id));
        return getSuccessResult(ret);
    }

    /**
     * 模板下载
     * */
    @RequestMapping("/exporttemplate")
    public void export(HttpServletResponse response){
        try {
            ExportBuilder builder = new ExportBuilder
                    (OrganizationImportTemplateBean.class,
                            new OrganizationParse()
                    );
            ExportFactory factory = ExportFactory.getExportFactory(
                    builder );
            factory.setDataList(new ArrayList<Organization>()).outPut(response);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 导入结果下载
     * */
    @RequestMapping("/down")
    public void importData(String fileKey,HttpServletResponse response){
            FileUtils.downFile(fileKey,response);
    }

    /**
     * 导入
     * */
    @RequestMapping("/import")
    public Result importData(@RequestParam("file") CommonsMultipartFile[] multipartFile){
        User user = getAuthUser();
        InputStream in = null;
        List<Organization> errList = null;
        List<String>errMsg = null;
        try {
            in=multipartFile[0].getInputStream();
            List<OrganizationImportTemplateBean>list=ImportUtil.getImportFactory(in).outResult(OrganizationImportTemplateBean.class);
            errList = new ArrayList<Organization>();
            errMsg = new ArrayList<String>();
            if(list != null && list.size() > 0){
                for (OrganizationImportTemplateBean bean:list){
                    OrganizationReq form=new OrganizationReq();
                    BeanUtils.copyProperties(form,bean);
                    List<String> msgList = validate(form);
                    Organization organization=convertBeanFromForm(form);

                    if(msgList == null || msgList.size() == 0){
                        try {
                            organization.setCreateUid(user.getId());
                            organization.setState(StateEnum.Valid.getState());
                            organizationService.add(organization);
                        }catch (BaseException e){
                            errMsg.add(e.getErrorMsg());
                            errList.add(organization);
                        }catch (Exception e){
                            errMsg.add(e.getMessage());
                            errList.add(organization);
                        }
                    }else{
                        StringBuffer msgStr = new StringBuffer();
                        for (String msg:msgList){
                            msgStr.append(msg+"||");
                        }
                        msgStr.replace(msgStr.lastIndexOf("||"),msgStr.length(),"");
                        errMsg.add(msgStr.toString());
                        errList.add(organization);
                    }
                }
            }
        }catch (Exception e){
            return getFailResult(BaseConstants.ERR_UNKOWN,e.getMessage());
        }
        finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(),e);
                }
            }
        }
        String fileKey = null;
        if(errList != null && errList.size()>0){
            String path = getRealPath("");
            File file = null;
            try {
                path += System.currentTimeMillis() +BaseConstants.DEFAULT_EXPORT_FILE_SUFFIX;
                file = new File(path);
                ExportBuilder builder = new ExportBuilder
                        (OrganizationImportTemplateBean.class,
                                new OrganizationParse()
                        );
                ExportFactory factory=ExportFactory.getExportFactory(
                        builder );
                factory.setErrMsgList(errMsg).setDataList(errList).outPut(file);
                fileKey = FileUtils.uploadFile("import/org/",file.getName(),file);
            }catch (Exception e){
                logger.error(e.getMessage(),e);
            }finally {
                if(file!=null){
                    file.delete();
                }
            }
        }
        return getSuccessResult(fileKey);
    }

}
